<template>
  <BasicModal
    width="60%"
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
    :showOkBtn="method != 'view'"
  >
    <a-descriptions :labelStyle="{ width: '120px' }" v-if="method == 'view'" :column="2" bordered>
      <a-descriptions-item label="产品名称">{{ info?.productDetailName }}</a-descriptions-item>
      <a-descriptions-item label="材料名称">{{ info?.productName }}</a-descriptions-item>
      <a-descriptions-item label="产品主图">
        <a-image :width="100" :src="info?.productDetailUrl" />
      </a-descriptions-item>
      <a-descriptions-item label="产品子图">
        <a-image v-for="item in info?.urlList" :key="item.sort" :width="100" :src="item?.picUrl" />
      </a-descriptions-item>
      <a-descriptions-item :span="2" label="产品介绍">
        {{ info?.productDetailIntroduce }}
      </a-descriptions-item>
      <a-descriptions-item :span="2" label="产品详情">{{
        info?.productDetail
      }}</a-descriptions-item>
    </a-descriptions>
    <BasicForm v-else @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { addFormSchema } from './index.data';
  import { addApi, updateApi, getInfoApi, getList } from '/@/api/product/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { ProductItem } from '/@/api/products/model';
  import { useRoute } from 'vue-router';
import { uploadApi } from '/@/api/sys/upload';
  export default defineComponent({
    name: 'AccountModal',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const method = ref('add');
      const rowId = ref('');
      const info = ref<ProductItem>({});
      const { createMessage } = useMessage();
      const route = useRoute();
      const addFormSchema: FormSchema[] = [
        {
          field: 'productDetailName',
          label: '产品名称',
          component: 'Input',
          colProps: { span: 12 },
          rules: [
            {
              required: true,
              message: '请输入材料名称',
            },
          ],
        },
        {
          field: 'productName',
          label: '材料名称',
          component: 'Input',
          show: false,
        },
        {
          field: 'productId',
          label: '材料名称',
          component: 'ApiSelect',
          required: true,
          colProps: { span: 12 },
          componentProps: ({ formModel }) => {
            return {
              api: getList,
              params: {
                pageSize: 999,
                pageNum: 1,
                zhCn: route.meta?.zhCn ?? 1,
              },
              resultField: 'records',
              labelField: 'productName',
              valueField: 'id',
              immediate: true,
              onChange: (e, option) => {
                formModel.productName = option?.label ?? '';
                formModel.productId = option?.value ?? ''
              },
              // atfer request callback
              onOptionsChange: (options) => {
                console.log('get options', options.length, options);
              },
            };
          },
        },
        {
          field: 'productDetailUrl',
          component: 'Upload',
          label: '产品主图',
          required: true,
          colProps: { span: 12 },
          componentProps: {
            api: uploadApi,
            maxNumber: 1,
            multiple: false,
            accept: ['image/*'],
            uploadParams: {
              videoFlag: false,
            },
          },
        },
        {
          field: 'urlList',
          component: 'Upload',
          label: '产品子图',
          colProps: { span: 12 },
          required: true,
          componentProps: {
            api: uploadApi,
            maxNumber: 5,
            multiple: true,
            accept: ['image/*'],
            uploadParams: {
              videoFlag: false,
            },
          },
        },
        {
          field: 'productDetailIntroduce',
          label: '产品介绍',
          component: 'InputTextArea',
          required: true,
        },
        {
          field: 'productDetail',
          label: '产品详情',
          component: 'InputTextArea',
          required: true,
        },
      ];
      const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
        labelWidth: 100,
        schemas: addFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 23,
        },
      });
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();

        setModalProps({ confirmLoading: false });
        method.value = data?.method;

        if (unref(method) == 'view' || unref(method) == 'edit') {
          const res = await getInfoApi({
            id: data.record.id,
            zhCn: route.meta?.zhCn ?? 1,
          });
          info.value = res;
          rowId.value = data.record.id;
          setFieldsValue({
            ...res,
            productDetailUrl: [res.productDetailUrl],
            urlList: res.urlList.map((item) => item.picUrl),
          });
        }
      });

      const getTitle = computed(() => {
        if (unref(method) == 'view') {
          return '查看';
        }
        if (unref(method) == 'edit') {
          return '编辑';
        }
        return '新增';
      });

      async function handleSubmit() {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });
          if (method.value == 'edit') values.id = rowId.value;
          values.productDetailUrl = values.productDetailUrl[0];
          values.urlList = values.urlList.map((item) => {
            return {
              picUrl: item,
            };
          });
          values.zhCn = route.meta?.zhCn ?? 1;
          method.value == 'edit' ? await updateApi(values) : await addApi(values);
          createMessage.success('操作成功');
          closeModal();
          emit('success', { method: unref(method), values: { ...values, id: rowId.value } });
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }
      return { registerModal, registerForm, getTitle, handleSubmit, info, method };
    },
  });
</script>
